package org.fjsei.yewu.jyjc;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.rs.sm.Decoder;
import com.rs.sm.Encoder;
//import com.seip.common.core.constant.SecurityConstants;
//import com.seip.common.core.utils.DateUtils;
//import com.seip.common.core.utils.IdUtils;
//import com.seip.common.core.utils.JwtUtils;
//import com.seip.common.core.utils.SpringUtils;
//import com.seip.common.redis.service.RedisService;
//import com.seip.common.security.utils.SecurityUtils;
//import com.seip.open.config.dtconfig.domain.DtBusiRequest;
//import com.seip.open.config.dtconfig.domain.DtBusiResponse;
//import com.seip.open.config.dtconfig.domain.DtMain;
import io.netty.channel.ConnectTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
//import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 作为服务提供者公共方法
 *
 * @author zjq
 * @date 2022-9-30
 */
@Slf4j
public class DtHandleUtil {

    private static final String DT_TOKEN_CACHE_KEY_PREFIX = "DT_TOKEN:";

    /**
     * 数据交换主表得key
     */
    private static final String DT_MAIN_CACHE_KEY_PREFIX = "DT_MAIN:";

    /**
     * 数据交换明细表的key
     */
    private static final String DT_DET_CACHE_KEY_PREFIX = "DT_DET:";

    /**
     * 数据交换对应字段的key
     */
    private static final String DT_FIELD_CACHE_KEY_PREFIX = "DT_FIELD:";

    /**
     * 数据交换数据字典的key
     */
    private static final String DT_DICT_CACHE_KEY_PREFIX = "DT_DICT:";

    /**
     * 跟总局特种设备检验数据平台数据交换的token
     */
    public static String DT_CNSETOKEN_CACHE_KEY_PREFIX = "DT_TOKEN_CNSE:";

    /**
     * 省局特种设备智慧监管平台数据交换token
     */
    public static String DT_JYJCTOKEN_CACHE_KEY_PREFIX = "DT_TOKEN_JYJC:";

    /**
     * 重放请求时间3分钟，ms
     */
    private static final Long REPLAY_REQ_TIME = Long.valueOf(180000);

    /**
     * 成功
     */
    public static int I_ERROR_SUCCESS = 0;

    /**
     * token失效
     */
    public static int I_ERROR_TOKEN = -1;

    /**
     * 解密失败
     */
    public static int I_ERROR_SM = -2;

    /**
     * 业务处理失败
     */
    public static int I_ERROR_EXCEPTION = -3;


    /**
     * 请求数据处理，解密数据，返回具体业务数据
     *
     * @param dtBusiRequest
     * @return
     */
//    public static Map DtRequestHandle(DtBusiRequest dtBusiRequest) {
//        Map<String, Object> retMap = new HashMap<String, Object>();
//        //接口应用代码
//        String dtCode = dtBusiRequest.getDtCode();
//        //接口应用名称
//        String dtUserName = dtBusiRequest.getDtUserName();
//        //用户校验获取的token
//        String dtToken = dtBusiRequest.getDtToken();
//        //时间戳
//        Long timeStamp = dtBusiRequest.getTimeStamp();
//        //用sm2加密后的sm4Key
//        String smKey = dtBusiRequest.getSmKey();
//        //用sm4Key加密后的业务数据
//        String busiData = dtBusiRequest.getBusiData();
//        //根据dtCode判断Token是否有效
//        String cacheDtToken = DtHandleUtil.getCacheDtCode(dtToken);
//        if (Objects.isNull(cacheDtToken) && StringUtils.equals("", cacheDtToken)) {
//            retMap.put("retCod", I_ERROR_TOKEN);
//            retMap.put("retDesc", "dtToken失效，请重新授权获取");
//            return retMap;
//        }
//
//        if (!StringUtils.equals(dtCode, cacheDtToken)) {
//            retMap.put("retCod", I_ERROR_TOKEN);
//            retMap.put("retDesc", "dtToken无效，请重新授权获取");
//            return retMap;
//        }
//        //判断是否重放请求
//        if (compareTimeStamp(timeStamp)) {
//            retMap.put("retCod", "-1");
//            retMap.put("retDesc", "重复请求，请核实");
//            return retMap;
//        }
//        //用sm2私匙解密获取sm4Key
//        DtMain dtMain = SpringUtils.getBean(RedisService.class).getCacheObject(DtHandleUtil.getMainKey(dtCode));
//        String sm4Key = SecurityUtils.decryptSM2Plus(smKey, dtMain.getDtSecretKey(), dtMain.getDtPublicKey());
//        //用sm4Key解密业务数据
//        String desBusiData = SecurityUtils.decryptSM4Plus(busiData, sm4Key);
//        retMap.put("retCod", I_ERROR_SUCCESS);
//        retMap.put("retDesc", "校验成功");
//        retMap.put("sm4Key", sm4Key);
//        retMap.put("busiData", desBusiData);
//        return retMap;
//    }


    /**
     * 接口服务数据响应，解密返回数据
     *
     * @param dtCode
     * @param retCode
     * @param retDesc
     * @param busiData
     * @return
     */
//    public static DtBusiResponse DtResponseHandle(String dtCode, String retCode, String retDesc, String busiData) {
//        DtBusiResponse dtBusiResponse = new DtBusiResponse();
//        dtBusiResponse.setRetCode(retCode);
//        dtBusiResponse.setRetDesc(retDesc);
//        DtMain dtMain = SpringUtils.getBean(RedisService.class).getCacheObject(DtHandleUtil.getMainKey(dtCode));
//        String sm4Key = SecurityUtils.getSecretSm4HexKey();
//        //sm4Key加密
//        String smKey = SecurityUtils.encryptSM2Plus(sm4Key, dtMain.getDtPublicKey());
//        //dtBusiResponse.setSmKey(smKey);
//        if (Objects.nonNull(busiData) && !"".equals(busiData)) {
//            dtBusiResponse.setBusiData(SecurityUtils.encryptSM4Plus(busiData, sm4Key));
//        }
//        return dtBusiResponse;
//    }


    public static boolean compareTimeStamp(Long timeStamp) {
        //时间戳大于3分钟，表示恶意调用，防重放攻击，但由于服务器时间差异，存在误差
        Boolean ret = false;
        Long currTimeStamp = System.currentTimeMillis();
        Long dec = currTimeStamp - timeStamp;
        if (dec > REPLAY_REQ_TIME) {
            ret = true;
        }
        return ret;
    }


    public static String getCacheDtCode(String dtToken) {
//        return SpringUtils.getBean(RedisService.class).getCacheObject(getKey(dtToken));
        return "";
    }

    public static String getKey(String dtCode) {
        return DT_TOKEN_CACHE_KEY_PREFIX.concat(dtCode);
    }

    public static String getMainKey(String dtCode) {
        return DT_MAIN_CACHE_KEY_PREFIX.concat(dtCode);
    }

    public static String getDtDelKey(Long tenantId, String dtCode, String apiName) {
        return DT_DET_CACHE_KEY_PREFIX.concat(String.valueOf(tenantId)).concat(dtCode).concat(".").concat(apiName);
    }

    public static String getDtMatchFieldKey(Long apiId, String busiType) {
        return DT_FIELD_CACHE_KEY_PREFIX.concat(String.valueOf(apiId)).concat(".").concat(busiType);
    }

    public static String getDtMatchDictKey(String dtCode, String dtType) {
        return DT_DICT_CACHE_KEY_PREFIX.concat(dtCode).concat(".").concat(dtType);
    }

    /**
     * 外部服务的token set
     */
    public static void setCacheOutDtToken(String cacheKey, String tokenValue, Long outTimeInMinutes) {
//        SpringUtils.getBean(RedisService.class).setCacheObject(cacheKey, tokenValue, outTimeInMinutes * 60, TimeUnit.SECONDS);
    }



    /**
     * 检验监察httpPost请求
     */
    public static Map<String, String> callJcHttpPost3(String dtUserName, String dtUserPsw, String url, String reqData, String token) {
        Map<String, Object> repMap = new HashMap<>();
        Map<String, String> respMapInfo = new HashMap<>();
        try {
            log.info("请求url： url={}", url);
            HttpRequest httpRequest = HttpUtil.createPost(url);
            httpRequest.header("Accept", "*/*");
            httpRequest.header("Content-Type", "application/json;charset=UTF-8");
            httpRequest.header("accessToken", token);
//            long time_stamp = System.currentTimeMillis();
//            Map<String, String> reqMap = new HashMap<>();
//            reqMap.put("username", username);
//            reqMap.put("passwd", pwd_encode);
//            reqMap.put("time_stamp", String.valueOf(time_stamp));
            httpRequest.header("accessDate", "1731157010163");
//            httpRequest.header("accessDate", DateUtils.getTime());  //dateTimeNow(YYYY_MM_DD_HH_MM_SS);"2024-11-09 20:42:22"
            //请求数据加密
            String sm4Key = Encoder.sm3(dtUserName + ":" + dtUserPsw);
            sm4Key = sm4Key.substring(0, 16);
            String encryReqData = Encoder.ecb(reqData, sm4Key);
            repMap.put("PARAMS", encryReqData);
            httpRequest.body(JSON.toJSONString(repMap), ContentType.JSON.getValue());
            httpRequest.setConnectionTimeout(10000);
            HttpResponse resp = httpRequest.execute();
            int retCod = resp.getStatus();
            if (retCod == 200) {
                String respInfo = resp.body();
                log.debug("请求响应： {}", respInfo);
                JSONObject jsonObject = JSON.parseObject(respInfo);
                if (jsonObject.getInteger("STATUS") == 0 || jsonObject.getInteger("STATUS") == 500) {
                    //请求失败
                    respMapInfo.put("retCod", "0");
                    respMapInfo.put("msg", jsonObject.get("MSG") == null ? "监察返回为空" : jsonObject.get("MSG").toString());
                } else {
                    //请求成功
                    respMapInfo.put("retCod", "1");
                    respMapInfo.put("msg", jsonObject.get("MSG").toString());
                    respMapInfo.put("TOTAL", jsonObject.get("TOTAL") == null ? "" : jsonObject.get("TOTAL").toString());
                }
                if (jsonObject.get("DATA") != null) {
                    respMapInfo.put("retData", Decoder.ecb(jsonObject.get("DATA").toString(), sm4Key));
                }
            } else {
                respMapInfo.put("retCod", "0");
                respMapInfo.put("msg", String.valueOf(retCod));
            }
        } catch (Exception e) {
            // 请求异常
            respMapInfo.put("retCod", "0");
            respMapInfo.put("msg", "请求监察异常:" + e.getMessage());
            log.error("请求监察异常：" + e.getMessage());
        }

        return respMapInfo;
    }

    public static <R> R postForObject(String url, Object body, int timeout, TypeReference<R> typeReference) {
//        final String bodyStr = body instanceof String ? (String) body : JSON.toJSONString(body);
        final String bodyStr ="{\"ACCESS_DATE\":\"2024-11-09 19:19:57\",\"PASSWD\":\"A#\",\"username\":\"ta_shengji_user\"}";
        final String respBody = HttpUtil.post(url, bodyStr,timeout);
        log.info("请求福建监察接口， url：" + url + "，参数：" + bodyStr + "，返回：" + respBody);
        return JSON.parseObject(respBody, typeReference);
    }
        //登录 token?
    public static Map<String, String> callJcHttpPostLogin(String dtUserName, String dtUserPsw, String url, String reqData, String token) {
        Map<String, Object> repMap = new HashMap<>();
        Map<String, String> respMapInfo = new HashMap<>();
        try {
            log.info("请求url： url={}", url);
            HttpRequest httpRequest = HttpUtil.createPost(url);
            httpRequest.header("Accept", "*/*");
            httpRequest.header("Content-Type", "application/json;charset=UTF-8");
            httpRequest.header("username", "ta_shengji_user");
            httpRequest.header("passwd", token);
            httpRequest.header("accessDate", "2024_11_09_17_22_22");
//            httpRequest.header("accessDate", DateUtils.getTime());  //dateTimeNow(YYYY_MM_DD_HH_MM_SS);

//            qparams.add(new BasicNameValuePair("username", username));// 需要对应传参的name和value
//            qparams.add(new BasicNameValuePair("passwd", pwd_encode));
//            qparams.add(new BasicNameValuePair("time_stamp", String.valueOf(time_stamp)));// 需要对应传参的name和value

            //请求数据加密
            String sm4Key = Encoder.sm3(dtUserName + ":" + dtUserPsw);
            sm4Key = sm4Key.substring(0, 16);
            String encryReqData = Encoder.ecb(reqData, sm4Key);
            repMap.put("PARAMS", encryReqData);

//            repMap.put("username", "ta_shengji_user");

            httpRequest.body(JSON.toJSONString(repMap), ContentType.JSON.getValue());
            httpRequest.setConnectionTimeout(10000);
            HttpResponse resp = httpRequest.execute();
            int retCod = resp.getStatus();
            if (retCod == 200) {
                String respInfo = resp.body();
                log.debug("请求响应： {}", respInfo);
                JSONObject jsonObject = JSON.parseObject(respInfo);
                if (jsonObject.getInteger("STATUS") == 0 || jsonObject.getInteger("STATUS") == 500) {
                    //请求失败
                    respMapInfo.put("retCod", "0");
                    respMapInfo.put("msg", jsonObject.get("MSG") == null ? "监察返回为空" : jsonObject.get("MSG").toString());
                } else {
                    //请求成功
                    respMapInfo.put("retCod", "1");
                    respMapInfo.put("msg", jsonObject.get("MSG").toString());
                    respMapInfo.put("TOTAL", jsonObject.get("TOTAL") == null ? "" : jsonObject.get("TOTAL").toString());
                }
                if (jsonObject.get("DATA") != null) {
                    respMapInfo.put("retData", Decoder.ecb(jsonObject.get("DATA").toString(), sm4Key));
                }
            } else {
                respMapInfo.put("retCod", "0");
                respMapInfo.put("msg", String.valueOf(retCod));
            }
        } catch (Exception e) {
            // 请求异常
            respMapInfo.put("retCod", "0");
            respMapInfo.put("msg", "请求监察异常:" + e.getMessage());
            log.error("请求监察异常：" + e.getMessage());
        }

        return respMapInfo;
    }

    public static String gettoken(Map busiMap) {
        final String JC_HOST = "220.160.53.129:18093";//NEW
//        final String JC_HOST = "220.160.53.129:18093"; "211.138.144.118:19000";//NEW
        Map<String, String> respMapInfo = new HashMap<>();
        // String url = "http://27.151.117.67:16882/jyfw/service/auth";
        String username = (String) busiMap.get("user_name");
        String passwd = (String) busiMap.get("passwd");
        String pwd_encode = Encoder.sm3(passwd);
        // String time_stamp = new FjseiDateTime().GetSysdateTimeS();
        long time_stamp = System.currentTimeMillis();
        Map<String, String> reqMap = new HashMap<>();
        reqMap.put("username", username);
        reqMap.put("passwd", pwd_encode);
        reqMap.put("time_stamp", String.valueOf(time_stamp));
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("username", username));// 需要对应传参的name和value
        qparams.add(new BasicNameValuePair("passwd", pwd_encode));
        qparams.add(new BasicNameValuePair("time_stamp", String.valueOf(time_stamp)));// 需要对应传参的name和value
        java.net.URI uri = null;
        try {
            uri = URIUtils.createURI("https", JC_HOST, -1, "/seds-gateway/api/det/service/auth", URLEncodedUtils.format(qparams, "UTF-8"), null);
            //   /seds-svc/
            //            uri = URIUtils.createURI("https", JC_HOST, -1, "/seds-gateway/api/det/service/auth", URLEncodedUtils.format(qparams, "UTF-8"), null);
            HttpPost httpPost = new HttpPost(uri);
            CloseableHttpClient client = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();
            // 请求参数转JOSN字符串
            UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(qparams, "UTF-8");
            reqEntity.setContentEncoding("UTF-8");
            reqEntity.setContentType("application/json");
            httpPost.setEntity(reqEntity);
            httpPost.setConfig(requestConfig);// 设置超时时间
            httpPost.setHeader("Accept", "*/*");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            CloseableHttpResponse resp = client.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() == 200) {
                String respInfo = EntityUtils.toString(resp.getEntity(), "UTF-8");
                // Map result = new ObjectMapper().readValue(respInfo,
                // Map.class);// json转为Map

                Map result = (Map) JSONUtils.decode(respInfo);
                String success = result.get("success").toString();
                ArrayList datas = (ArrayList) result.get("data");
                Map tkmap = (Map) datas.get(0);
                String res= (String) tkmap.get("token");
                return res;
            }
            else {
                respMapInfo.put("retCod", "-1");
                respMapInfo.put("retData", "访问监察平台接口失败");
            }
        }
        catch (ConnectTimeoutException ex) {
            // 请求连接超时
            respMapInfo.put("retCod", "-1");
            respMapInfo.put("retData", "请求超时");
        }
        catch (Exception e) {
            // 请求异常
            respMapInfo.put("retCod", "-1");
            respMapInfo.put("retData", "请求异常");
        }
        return null;
    }

    public static Map callHttpService(Map busiMap) {
        final String JC_HOST = "220.160.53.129:18093";//NEW
        Map<String, String> respMapInfo = new HashMap<>();
        String token = "";
        // 根据监察机构和检验机构id获取用户名和密码
//        Result resultSql = new Result();
        String user_name = "";
        String passwd = "";
        //String ISPUNT_ID = busiMap.get("ISPUNT_ID").toString();
        //String JG_UNT_ID = busiMap.get("JG_UNT_ID").toString();
        StringBuffer sqlSB = new StringBuffer();
        ArrayList<Object> label = new ArrayList<Object>();
		/*label.add(ISPUNT_ID);
		label.add(JG_UNT_ID);
		sqlSB.append("SELECT A.JC_USER_ID, REPLACE(FROM_BASE64(A.JC_USER_PSW), B.PSW_KEY, '') AS JC_USER_PSW\n");
		sqlSB.append("  FROM TB_JGUNT_ACC A, TB_JCUNT_INFO B\n");
		sqlSB.append(" WHERE A.JG_UNT_ID = B.JG_UNT_ID\n");
		sqlSB.append("   AND A.ISPUNT_ID = ?\n");
		sqlSB.append("   AND A.JG_UNT_ID = ?\n");
		resultSql = (new DBSql()).executeSql(sqlSB.toString(), label);
		if (resultSql.iErrorCode == 0 && resultSql.iSum > 0) {
			user_name = resultSql.aaMultiLinesOut[0][0];
			passwd = resultSql.aaMultiLinesOut[0][1];
		}*/
        user_name = "福分部";
        passwd = "";
        busiMap.put("user_name", user_name);
        busiMap.put("passwd", passwd);
//        Map msg = gettoken(busiMap);
//        String retCod = (String) msg.get("retCod");
//        if (retCod.equals("0")) {
//            token = (String) ((Map) JSON.Decode((String) msg.get("data"))).get("token");
//        }
//        else {
//            respMapInfo.put("retCod", "-1");
//            respMapInfo.put("retData", (String) msg.get("retData"));
//            return respMapInfo;
//        }
        // String token = busiMap.get("token").toString();
        //String SM3_KEY = Encoder.sm3(user_name + ":" + passwd);
		/*String key2="";
		try {
			String resultString = new String(":".getBytes("gbk"),"utf-8");
			 key2= Encoder.sm3(resultString);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}*/
        //String key= Encoder.sm3(""+":"+"");
        // String rdata = busiMap.get("rdata").toString();
        String SM3_KEY ="806b4179dea7021768e97e93183d8628d9391bd461b6662c750894b1066c44e3";
        String ope_cod ="regeqpquery";  // busiMap.get("ope_cod").toString();
        busiMap.remove(ope_cod);
        busiMap.remove(user_name);
        busiMap.remove(passwd);
//        Sm4UtilsJC sm4 = new Sm4UtilsJC();
//        String encode_data = sm4.SM4_ENCRYPT_RS(JSON.Encode(busiMap), SM3_KEY);// 修改SM4
//        // String decode_data = sm4.SM4_DECRYPT_RS(encode_data, SM3_KEY);
//        String time_stamp = new FjseiDateTime().GetSysdateTimeS();

        //请求数据加密
        String sm4Key = Encoder.sm3(user_name + ":" + passwd);
        sm4Key = sm4Key.substring(0, 16);
        String reqData="";
        String encryReqData = Encoder.ecb(reqData, sm4Key);
//        repMap.put("PARAMS", encryReqData);
//        httpRequest.body(JSON.toJSONString(repMap), ContentType.JSON.getValue());
//        String url = ComCfg.JcserverUrl + "service/api/" + ope_cod;
        long time_stampl = System.currentTimeMillis();
        String time_stamp= String.valueOf(time_stampl);
        Map<String, String> reqMap = new HashMap<>();
        reqMap.put("encode_data", encryReqData);
        reqMap.put("time_stamp", time_stamp);
        reqMap.put("token", token);
        // String signnature = Digital.sing(encode_data,
        // "91350203M0001ACA11测试-02_5", "RSYZ", "114.115.172.176", 8088);
        String signnature = "";
        reqMap.put("signnature", signnature);
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("encode_data", encryReqData));// 需要对应传参的name和value
        qparams.add(new BasicNameValuePair("time_stamp", time_stamp));
        qparams.add(new BasicNameValuePair("token", token));
        qparams.add(new BasicNameValuePair("ope_cod", ope_cod));
        qparams.add(new BasicNameValuePair("signnature", signnature));
        java.net.URI uri = null;
        try {
            uri = URIUtils.createURI("https",
                    JC_HOST, -1, "/seds-gateway/api/det/service/api/" + ope_cod, URLEncodedUtils.format(qparams, "UTF-8"), null);
            HttpPost httpPost = new HttpPost(uri);
            CloseableHttpClient client = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(100000).setConnectionRequestTimeout(100000).setSocketTimeout(100000).build();
            // 请求参数转JOSN字符串
            UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(qparams, "UTF-8");
            reqEntity.setContentEncoding("UTF-8");
            reqEntity.setContentType("application/json");
            httpPost.setEntity(reqEntity);

            httpPost.setHeader("Accept", "*/*");
            httpPost.setConfig(requestConfig);// 设置超时时间
            var resp =  client.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() == 200) {
                String respInfo = EntityUtils.toString(resp.getEntity());
//                // Map result = new ObjectMapper().readValue(respInfo,
//                // Map.class);// json转为Map
//                Map result = (Map) JSON.Decode(respInfo);
//                String success = result.get("success").toString();
//                if (success.equals("true")) {
//                    respMapInfo.put("retCod", "0");
//                    String data = result.get("data") == null ? "" : result.get("data").toString();
//                    data = data == "" ? "" : sm4.SM4_DECRYPT_RS(data, SM3_KEY);
//                    respMapInfo.put("retData", data);
//                    // 如果返回的是true，data需要解析
//                }
//                else {
//                    respMapInfo.put("retCod", "-1");
//                    respMapInfo.put("retData", result.get("message").toString());
//                }
                return respMapInfo;
            }
            else {
                respMapInfo.put("retCod", "-1");
                respMapInfo.put("retData", "访问监察接口服务失败");
            }
        }
        catch ( ConnectTimeoutException ex) {
            // 请求连接超时
            respMapInfo.put("retCod", "-1");
            respMapInfo.put("retData", "请求超时");
        }
        catch (Exception e) {
            // 请求异常
            respMapInfo.put("retCod", "-1");
            respMapInfo.put("retData", "请求异常");
        }
        return respMapInfo;
    }
    public static Map callHttpServicenew(Map busiMap,String token) throws JsonProcessingException {
        Map<String, String> respMapInfo = new HashMap<>();
//        String token = "9bc801235e9ad1f9b76fe15732d513ba";
        String user_name = "";
        String passwd = "";
        StringBuffer sqlSB = new StringBuffer();
        ArrayList<Object> label = new ArrayList<Object>();
        user_name= "det_test";
        passwd="02830323ce234912e368947f007a7aea";
        busiMap.put("user_name", user_name);
        busiMap.put("passwd", passwd);
//        Map msg = gettokennew(busiMap);
//        String retCod = (String) msg.get("retCod");
//        if (retCod.equals("0")) {
//            token = (String) ((Map) JSON.Decode((String) msg.get("data"))).get("TOKEN");
//        }
//        else {
//            respMapInfo.put("retCod", "-1");
//            respMapInfo.put("retData", (String) msg.get("retData"));
//            return respMapInfo;
//        }
        String SM3_KEY = Encoder.sm3(user_name + ":" + passwd);
//        String apiName ="/api/det/inspect/check/updateInfo"; //busiMap.get("apiName").toString();
        String apiName ="/api/det/inspect/check/updateInfo";
        busiMap.remove("apiName");
        busiMap.remove("user_name");
        busiMap.remove("passwd");
//        Sm4UtilsJC sm4 = new Sm4UtilsJC();
        String toencs=JSONUtils.encode(busiMap);
        String sm4Key = Encoder.sm3(user_name + ":" + passwd);
        sm4Key = sm4Key.substring(0, 16);
        String encode_data = Encoder.ecb(toencs, sm4Key);

//        String encode_data ="";// sm4.SM4_ENCRYPT_RS(toencs, SM3_KEY);// 修改SM4
//        String time_stamp = new FjseiDateTime().GetSysdateTime();
        //String JcserverUrl = "http://27.151.117.67:16882/jyfw";
    //    String JcserverUrl ="https://220.160.53.129:18093/seds-gateway"; 产品的
        String JcserverUrl ="http://211.138.144.118:19000/seds-svc";
        String url =JcserverUrl + apiName;
        Map<String, String> reqMap = new HashMap<>();
        reqMap.put("PARAMS",encode_data);
        try {
            HttpPost httpPost = new HttpPost(url);
            CloseableHttpClient client = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(100000).setConnectionRequestTimeout(100000).setSocketTimeout(100000).build();

            StringEntity reqEntity = new StringEntity(JSONUtils.encode(reqMap),"UTF-8");
            //            StringEntity reqEntity = new StringEntity(JSON.Encode(reqMap),"UTF-8");
            reqEntity.setContentEncoding("UTF-8");
            reqEntity.setContentType("application/json");
            httpPost.setEntity(reqEntity);
            httpPost.setHeader("Accept", "*/*");
            httpPost.setHeader("accessToken", token);
            httpPost.setHeader("accessDate", GetSysdateTime());

//            httpPost.setHeader("accessDate", "2024-11-09 19:19:57");
//            httpPost.setHeader("accessDate", time_stamp);
            httpPost.setConfig(requestConfig);// 设置超时时间
            var resp = client.execute(httpPost);
            int ret=resp.getStatusLine().getStatusCode();
            if (resp.getStatusLine().getStatusCode() >0) {
                String respInfo = EntityUtils.toString(resp.getEntity());
                Map result = (Map) JSONUtils.decode(respInfo);
                String status = result.get("STATUS").toString();
                if (status.equals("1")) {
                    respMapInfo.put("retCod", "0");
                    respMapInfo.put("retData", result.get("MSG").toString());
                }
                else {
                    respMapInfo.put("retCod", "-1");
                    respMapInfo.put("retData", result.get("MSG") != null ? result.get("MSG").toString():"");
                }
                return respMapInfo;
            }
            else {
                respMapInfo.put("retCod", "-1");
                respMapInfo.put("retData", "访问监察接口服务失败");
            }
        }
        catch ( ConnectTimeoutException ex) {
            respMapInfo.put("retCod", "-1");
            respMapInfo.put("retData", "请求超时");
        }
        catch (Exception e) {
            respMapInfo.put("retCod", "-1");
            respMapInfo.put("retData", "请求异常");
        }
        return respMapInfo;
    }
    public static String GetSysdateTime() {
        // 获取当前的日期和时间
        LocalDateTime now = LocalDateTime.now();
        // 创建一个日期时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 使用格式化器将 LocalDateTime 格式化为字符串
        String formattedDateTime = now.format(formatter);
        // 输出结果
        System.out.println(formattedDateTime);
        return formattedDateTime;        //2023-04-01 15:15:30
    }
    /**智慧pt》监察：
     * 检验监察httpPost请求
     * DtHandleUtil.callJcHttpPost(api.getDtUserName(), api.getDtUserPsw(), （api.getApiUrl() + api.getApiName()） , reqJsonData, token);
     */
    public static Map<String, String> callJcHttpPost(String dtUserName, String dtUserPsw, String url, String reqJsonData, String token) {
        Map<String, Object> repMap = new HashMap<>();
        Map<String, String> respMapInfo = new HashMap<>();
        try {
            log.info("请求url： url={}", url);
            HttpRequest httpRequest = HttpUtil.createPost(url);
            httpRequest.header("Accept", "*/*");
            httpRequest.header("Content-Type", "application/json;charset=UTF-8");
            httpRequest.header("accessToken", token);
            String timenow= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format( new Date());
            httpRequest.header("accessDate", timenow);
            //请求数据加密
            String sm4Key = Encoder.sm3(dtUserName + ":" + dtUserPsw);
            sm4Key = sm4Key.substring(0, 16);
            String encryReqData = Encoder.ecb(reqJsonData, sm4Key);
            repMap.put("PARAMS", encryReqData);
            httpRequest.body(JSON.toJSONString(repMap), ContentType.JSON.getValue());
            httpRequest.setConnectionTimeout(10000);
            HttpResponse resp = httpRequest.execute();
            int retCod = resp.getStatus();
            if (retCod == 200) {
                String respInfo = resp.body();
                log.debug("请求响应： {}", respInfo);
                JSONObject jsonObject = JSON.parseObject(respInfo);
                if (jsonObject.getInteger("STATUS") == 0 || jsonObject.getInteger("STATUS") == 500) {
                    //请求失败
                    respMapInfo.put("retCod", "0");
                    respMapInfo.put("msg", jsonObject.get("MSG") == null ? "监察返回为空" : jsonObject.get("MSG").toString());
                } else {
                    //请求成功
                    respMapInfo.put("retCod", "1");
                    respMapInfo.put("msg", jsonObject.get("MSG").toString());
                    respMapInfo.put("TOTAL", jsonObject.get("TOTAL") == null ? "" : jsonObject.get("TOTAL").toString());
                }
                if (jsonObject.get("DATA") != null) {
                    respMapInfo.put("retData", Decoder.ecb(jsonObject.get("DATA").toString(), sm4Key));
                }
            } else {
                respMapInfo.put("retCod", "0");
                respMapInfo.put("msg", String.valueOf(retCod));
            }
        } catch (Exception e) {
            // 请求异常
            respMapInfo.put("retCod", "0");
            respMapInfo.put("msg", "请求监察异常:" + e.getMessage());
            log.error("请求监察异常：" + e.getMessage());
        }

        return respMapInfo;
    }
    public static String decrypt(String source, String userName, String password) {
        String sm4Key = Encoder.sm3(userName + ":" + password);
        sm4Key = sm4Key.substring(0, 16);
        return Decoder.ecb(source, sm4Key);
    }
    public static String decrypt(String source, String sm4Key) {
        return Decoder.ecb(source, sm4Key);
    }
    public static String encrypt(String source, String userName, String password) {
        String sm4Key = Encoder.sm3(userName + ":" + password);
        sm4Key = sm4Key.substring(0, 16);
        return Encoder.ecb(source, sm4Key);
    }
    public static String encrypt(String source, String sm4Key) {
        return Encoder.ecb(source, sm4Key);
    }
}
